package com.bawei.mall.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.utils.JwtUtils;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.mall.user.domain.*;
import com.bawei.mall.user.mapper.AddressMapper;
import com.bawei.mall.user.mapper.ConfirMapper;
import com.bawei.mall.user.mapper.MallCusShopMapper;
import com.bawei.mall.user.service.ConfirService;
import com.bawei.system.domain.model.LoginUser;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Service
@Log4j
public class ConfirServiceImpl implements ConfirService {
    @Autowired
    private ConfirMapper confirMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MallCusShopMapper mallCusShopMapper;
    @Autowired
    private AddressMapper addressMapper;
//    @Autowired
//    private


    private static final String ACCESS_TOKEN="login_tokens:";

    /**
     *
     * @param ids
     * @return
     */
    @Override
    public R<ConfirmOrder> generateConfirmOrder(List<String> ids) {
        String token = SecurityUtils.getToken();
        String key = JwtUtils.getUserKey(token);
        String userKey = getTokenKey(key);
        String cusUserJSONString = redisTemplate.opsForValue().get(userKey);
        LoginUser loginUser= JSON.parseObject(cusUserJSONString, LoginUser.class);
        CusUser cusUser = loginUser.getCusUser();
        Integer userId = cusUser.getUserId();

        ConfirmOrder confirmOrder = new ConfirmOrder();

        List<MallProductCar> list = mallCusShopMapper.findByUserIdIdsList(userId,ids);
        ArrayList<MallProductCar> mallProductCars = new ArrayList<>();

        for (MallProductCar mallProductCar : list) {
            String sku1 = mallProductCar.getProductAttr();
            List<Map> list1 = new ArrayList<>();
            String[] split = sku1.split(",");
            for (int i = 0; i <split.length; i++) {
                Map map = new HashMap<>();
                map.put("key",i+1);
                map.put("value",split[i]);
                list1.add(map);
            }
            mallProductCar.setProductAttr(JSON.toJSONString(list1));
            mallProductCars.add(mallProductCar);
        }
        confirmOrder.setCartPromotionItemList(mallProductCars);

        List<Address> allAddress = addressMapper.findAllAddress();
        confirmOrder.setMemberReceiveAddressList(allAddress);

        //赋值integrationConsumeSetting
        IntegrationConsumeSetting integrationConsumeSetting = new IntegrationConsumeSetting();
        integrationConsumeSetting.setId(1);
        integrationConsumeSetting.setUseUnit(100);
        integrationConsumeSetting.setCouponStatus(1);
        integrationConsumeSetting.setMaxPercentPerOrder(50);
        integrationConsumeSetting.setDeductionPerAmount(100);
        confirmOrder.setIntegrationConsumeSetting(integrationConsumeSetting);

        /**
         * 金额
         */
        CalcAmount calcAmount = new CalcAmount();
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (MallProductCar mallProductCar : list) {
            BigDecimal price = mallProductCar.getPrice();
            totalAmount=totalAmount.add(price);
        }

        String discount = cusUser.getDiscount();
        if(discount!=null){
            //去除优惠百分比 去除% discount赋值
                if(discount.endsWith("%")){
                discount=discount.substring(0,discount.length()-1);
            }
            BigDecimal discountRate = new BigDecimal(discount).divide(BigDecimal.valueOf(100));

            //计算折扣金额
            BigDecimal discountAmount = totalAmount.multiply(discountRate);
            log.info("折扣金额：" + discountAmount);
            //会员优惠金额
            BigDecimal discountedTotalAmount = totalAmount.subtract(discountAmount);
            log.info("折扣后的总金额：" + discountedTotalAmount);
            //商品总金额
            calcAmount.setTotalAmount(totalAmount);
            //会员优惠金额
            calcAmount.setPromotionAmount(discountedTotalAmount);
            //实际付款
            calcAmount.setPayAmount(totalAmount.subtract(discountedTotalAmount));

        }
        confirmOrder.setCalcAmount(calcAmount);
        return R.ok(confirmOrder);

    }

    @Override
    public R<CusOrder> generateOrder(CusOrder cusOrder) {
        String token = SecurityUtils.getToken();
        String key = JwtUtils.getUserKey(token);
        String userKey = getTokenKey(key);
        String cusUserJSONString = redisTemplate.opsForValue().get(userKey);
        LoginUser loginUser= JSON.parseObject(cusUserJSONString, LoginUser.class);
        CusUser cusUser = loginUser.getCusUser();
        Integer userId = cusUser.getUserId();

        cusOrder.setUserId(userId);
//        Address address = addressMapper.findById(cusOrder.getId());
//        cusOrder.setAddressId(address.getId());

        mallCusShopMapper.generateOrder(cusOrder);
        return R.ok(cusOrder);
    }



    @Override
    public void AddMiddleOrder(Integer orderId, List<MallProductCar> mallProductCars) {
        mallCusShopMapper.AddMiddleOrder(orderId,mallProductCars);
    }

    @Override
    public PageInfo<MallOrderList> list(Integer status, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<MallOrderList> list = confirMapper.list(status);
        String token = SecurityUtils.getToken();
        String key = JwtUtils.getUserKey(token);
        String userKey = getTokenKey(key);
        String cusUserJSONString = redisTemplate.opsForValue().get(userKey);
        LoginUser loginUser= JSON.parseObject(cusUserJSONString, LoginUser.class);
        CusUser cusUser = loginUser.getCusUser();
        Integer userId = cusUser.getUserId();
        for (MallOrderList mallOrderList : list) {
            CompletableFuture<Integer> f1 =CompletableFuture.supplyAsync(()->{
                mallOrderList.setOrderItemList(confirMapper.findByIds());
                return 1;
            });

            CompletableFuture.allOf(f1).join();
        }
        PageInfo<MallOrderList> order = new PageInfo<>(list);
        return order;
    }
//    @Override
//    public List<CusOrder> list() {
//        String token = SecurityUtils.getToken();
//        String key = JwtUtils.getUserKey(token);
//        String userKey = getTokenKey(key);
//        String cusUserJSONString = redisTemplate.opsForValue().get(userKey);
//        LoginUser loginUser= JSON.parseObject(cusUserJSONString, LoginUser.class);
//        CusUser cusUser = loginUser.getCusUser();
//        Integer userId = cusUser.getUserId();
//        List<MallProductCar> list = mallCusShopMapper.findCusOrderList(userId);
//        return null;
//    }

    private String getTokenKey(String key) {
        return ACCESS_TOKEN + key;
    }
}
